package com.naire.modul.customer.service;

import java.io.File;
import java.util.List;

import net.common.service.GeneralService;
import net.common.util.FilePathUtils;
import net.common.util.XMLHandler;

import org.dom4j.Element;

import com.naire.modul.customer.dao.CustomerDao;
import com.naire.modul.customer.dao.impl.CustomerDaoImpl;
import com.naire.modul.customer.vo.CustomerVo;
import com.naire.modul.customer.vo.FieldVo;

public class CustomerSaveDefinedService extends GeneralService {

	private List<FieldVo> fields = null;
	private Integer cust_id;
	
	@Override
	public void execute() throws Exception {
		CustomerDao dao = new CustomerDaoImpl();
		XMLHandler xml = null;
		String text = dao.findText(cust_id);
		if(text == null) {
			text = FilePathUtils.getFilePath("/template/customer_org_defined.xml");
			xml = new XMLHandler(new File(text));
		} else {
			xml = new XMLHandler(text);
		}
		for(FieldVo fv : fields) {
			Element e = (Element) xml.selectSingleNode("fields/field[@id='" + fv.getId() + "']");
			e.attribute("name").setValue(fv.getName());
			e.attribute("length").setValue(String.valueOf(fv.getLength()));
			e.attribute("type").setValue(String.valueOf(fv.getType()));
		}
		CustomerVo c = new CustomerVo();
		c.setCust_id(cust_id);
		c.setCust_type(xml.toXml());
		dao.update(c);
	}

	public void setFields(List<FieldVo> fields) {
		this.fields = fields;
	}

	public void setCust_id(Integer cust_id) {
		this.cust_id = cust_id;
	}

}
